package com.petsbang.http;

import java.io.DataInputStream;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import com.petsbang.action.dao.DataApplication;
import com.petsbang.common.Common;
import com.petsbang.db.DataBase;
import com.petsbang.vo.PictureInfo;
import com.petsbang.vo.UserShareInfo;

public class DataThread extends Thread {
	private final String tag = "dataThread";
	private String url;
	private int type;
	private DataHandler dh;
	private Context context;
	
	private String pictureTag;
	
	DataBase db;
	Cursor cursor;
	
	public DataThread(Context context, String url, int type, String picTag) {
		dh = new DataHandler(context);
		this.url = url;
		this.type = type;
		this.pictureTag = picTag;
		this.context = context;
		db = new DataBase(context);
	}

	@Override
	public void run() {
		super.run();
		if (url == null || url.length() == 0) {
			Log.e(tag, "url不能空");
			return;
		}
		Message msg = new Message();
		Bundle mBundle = new Bundle();
		mBundle.putInt(Common.status_str, Common.status_error);
		try {
			try {
				mBundle = sendDataMessage();
			} catch (Exception e) {
				e.printStackTrace();
				if (type == Common.share_type) {
					DataApplication appState = (DataApplication) context.getApplicationContext();
					String indexStr = "data_url=";
					int indexLen = indexStr.length();
					String imageUrl = url.substring(url.indexOf(indexStr) + indexLen,
							url.indexOf("&data_title="));
					appState.getShareList().put(imageUrl, new ArrayList<UserShareInfo>());
					mBundle.putString("url", imageUrl);
				}
			}

		} finally {
			msg.what = type;
			msg.setData(mBundle);
			dh.sendMessage(msg);
			url = null;
		}
	}
	
	/**
	 * 
	 * @throws Exception
	 */
	public Bundle sendDataMessage() throws Exception {
		Bundle mBundle = new Bundle();
		mBundle.putInt(Common.status_str, Common.status_error);
		String cmwap = NetHelper.isConnectedInternet(context);
//		if (cmwap == null) {
//			
//			//type = Common.eror_type;
//			// DialogInfo.showWifiDialog((Activity)context);
//			mBundle.putInt(Common.status_str, Common.status_error);
//			return mBundle;
//		}

		HttpURLConnection httpConn = NetHelper.getHttpUrlConnection(url, cmwap);
		
		DataInputStream in = null;
		byte[] messageBtye = null;

		if (HttpURLConnection.HTTP_OK == httpConn.getResponseCode()) {
			in = new DataInputStream(httpConn.getInputStream());
			int length = 1024 * 200;
			if (length > 0) {
				messageBtye = NetHelper.readBytes(in, 0, length);
			}
			in.close();
		} else {
			System.out.println("**************");
		}

		if (messageBtye != null) {
			String json = new String(messageBtye, "UTF-8");
			if (type == Common.pic_type) {
				db.open();
				// 查询数据库
				cursor = db.queryPictureInfos(pictureTag);
				if (cursor == null || cursor.getCount() == 0) {
					parsePic(json);
					mBundle.putString("url", url);
				} else {
					getDataFromDatabase(cursor);
				}
				cursor.close();
				db.close();
			}

			if (type == Common.share_type || type ==  Common.more_share_type) {
				String indexStr = "data_url=";
				int indexLen = indexStr.length();
				String imageUrl = url.substring(url.indexOf(indexStr)
						+ indexLen, url.indexOf("&data_title="));
				mBundle.putString("url", imageUrl);
				parseShare(json);
			}
			mBundle.putInt(Common.status_str, Common.status_ringht);
		} else {
			mBundle.putInt(Common.status_str, Common.status_error);
		}

		return mBundle;
	}

	/**
	 * 解析图片信息
	 * @param json
	 * @throws JSONException
	 */
	public void parsePic(String json) throws JSONException {
		DataApplication appState = (DataApplication) context
				.getApplicationContext();

		if (appState.getPicList() == null) {
			appState.setPicList(new ArrayList<PictureInfo>());
		}

		JSONObject boot = new JSONObject(json);
		JSONArray jsonArray = boot.getJSONArray("data");
//		db.open();
		int length = jsonArray.length();
		for (int i = 0; i < length; i++) {
			JSONObject item = jsonArray.getJSONObject(i);
			PictureInfo tmpPic = new PictureInfo();
			try {
				tmpPic.setTimestamp(item.getInt(Common.TIMESTAMP));
				tmpPic.setId(item.getInt(Common.ITEM_ID));
				tmpPic.setThumbnail_url(item.getString(Common.THUMBNAIL_URL));
				tmpPic.setDesc(item.getString(Common.DESCRIPTION));
				tmpPic.setMiddle_url(item.getString(Common.MIDDLE_URL));
				tmpPic.setLarge_url(item.getString(Common.LARGE_URL));
				tmpPic.setWidth(item.getInt(Common.WIDTH));
				tmpPic.setHeight(item.getInt(Common.HEIGHT));
				tmpPic.setImage_height(item.getInt(Common.IMAGE_HEIGHT));
				tmpPic.setImage_width(item.getInt(Common.IMAGE_WIDTH));
				tmpPic.setShare_url(item.getString(Common.SHARE_URL));
				tmpPic.setComments_count(item.getInt(Common.COMMENTS_COUNT));
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}

			appState.getPicList().add(tmpPic);
			// 保存图片信息
			db.insertPictureInfos(pictureTag, tmpPic);
		}
//		db.close();
	}

	/**
	 * 解析评论信息
	 * @param json
	 * @throws JSONException
	 */
	public void parseShare(String json) throws JSONException {
		DataApplication appState = (DataApplication) context
				.getApplicationContext();

		ArrayList<UserShareInfo> dataArray = new ArrayList<UserShareInfo>();
		JSONObject boot = new JSONObject(json);
		String timestamp = "timestamp";
		String text = "text";
		String user_profile_image_url = "user_profile_image_url";
		String platform = "platform";
		String user_name = "user_name";

		JSONArray jsonArray = boot.getJSONArray("data");

		int length = jsonArray.length();
		for (int i = 0; i < length; i++) {
			JSONObject item = jsonArray.getJSONObject(i);
			UserShareInfo userInfo = new UserShareInfo();
			try {
				userInfo.setText(item.getString(text));
				userInfo.setUser_profile_image_url(item.getString(user_profile_image_url));
				userInfo.setPlatform(item.getString(platform));
				userInfo.setUser_name(item.getString(user_name));
				userInfo.setTimestamp(item.getString(timestamp));

			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}
			dataArray.add(userInfo);
		}
		String indexStr = "data_url=";
		int indexLen = indexStr.length();
		String imageUrl = url.substring(url.indexOf(indexStr) + indexLen,
				url.indexOf("&data_title="));
		
		if (appState.getShareList().containsKey(imageUrl)) {
			ArrayList<UserShareInfo> tmpList = appState.getShareList().get(imageUrl);
			if (tmpList == null || tmpList.size() == 0) {
				appState.getShareList().put(imageUrl, dataArray);
			}else{
				tmpList.addAll(dataArray);
			}
		}else{
			appState.getShareList().put(imageUrl, dataArray);
		}
	}

	/**
	 * 解析评论信息
	 * @param json
	 * @throws JSONException
	 */
	public void getDataFromDatabase(Cursor cursor) throws JSONException {
		DataApplication appState = (DataApplication) context
				.getApplicationContext();

		ArrayList<PictureInfo> picInfosList = appState.getPicList();
		if (picInfosList == null) {
			picInfosList = new ArrayList<PictureInfo>();
		}
		if (cursor == null) {
			return;
		}
		/*
		int size = cursor.getCount();
		cursor.moveToFirst();
		for (int i=0; i<size; i++) {
			System.out.println(cursor.getString(11)); // share_url
			System.out.println(cursor.getString(12)); // comments_count
			System.out.println(cursor.getString(13)); //desc
			cursor.moveToNext();
		}
		cursor.moveToFirst();*/
		while (cursor.moveToNext()) {
			
			PictureInfo tmpPic = new PictureInfo();
			tmpPic.setId(cursor.getInt(cursor.getColumnIndex(Common.ITEM_ID)));
			tmpPic.setTimestamp(cursor.getInt(cursor.getColumnIndex(Common.TIMESTAMP)));
			tmpPic.setDesc(cursor.getString(cursor.getColumnIndex(Common.DESCRIPTION)));
			tmpPic.setImage_height(cursor.getInt(cursor.getColumnIndex(Common.IMAGE_HEIGHT)));
			tmpPic.setImage_width(cursor.getInt(cursor.getColumnIndex(Common.IMAGE_WIDTH)));
			tmpPic.setMiddle_url(cursor.getString(cursor.getColumnIndex(Common.MIDDLE_URL)));
			tmpPic.setLarge_url(cursor.getString(cursor.getColumnIndex(Common.LARGE_URL)));
			tmpPic.setFavor(cursor.getInt(cursor.getColumnIndex(Common.FAVOR)));
			picInfosList.add(tmpPic);
		}

		appState.setPicList(picInfosList);
		cursor.close();
	}
}
